import React, { Component } from 'react'
import { getContext } from '@/context/common/applicationContext'
import EditorWidget from '@/components/basicWidget/EditorWidget/index.js'
import { Spin, message } from 'antd'
import InputWidget from '@/components/basicWidget/InputWidget/index.js'
import CheckBoxWidget from '@/components/basicWidget/CheckBoxWidget/index.js'
import Button from '@/components/basicWidget/Button/index.js'
import { withRouterContext } from '@/context/router/routerContext.js'
import { post, get } from '@/utils/requestUtil.js'
import { getDocumentsByCondition } from '@/service/document/documentService'

import './index.css'

class WriteBlog extends Component {

    constructor(props) {
        super(props)
        this.state = {
            loading: true,
            user: null,
            blog: { id: null },
            personClass: [], //个人分类
            customerBlogClass: [], //博客所属的个人分类
        }
    }

    async componentDidMount() {
        const { user } = this.props //用户信息
        const { id } = this.props.routerParams //路由中blog的id
        let blog = { id: null }

        if (id) { //路由中id存在说明是要修改博客
            const response = await get(`/blog/get/${id}`)
            if (response && response.data) blog = response.data
        }

        //获取用户名下的自定义博客分类
        let personClass = []
        if (user) {
            const response = await getDocumentsByCondition({
                serviceName: 'blog',
                collectionName: 'customer_blogclass_info',
                searchFactory: [
                    {
                        fieldName: 'customerId',
                        fieldValue: user.id,
                        operate: 'eq'
                    }
                ]
            })
            if (response && response.data) {
                personClass = response.data.map(item => {
                    return item.content
                })
            }
        }

        //获取博客所属个人分类
        let customerBlogClass = []
        if (id) {
            const response = await getDocumentsByCondition({
                serviceName: 'blog',
                collectionName: 'customer_blogclass_blog_info',
                searchFactory: [
                    {
                        fieldName: 'blogId',
                        fieldValue: id,
                        operate: 'eq'
                    }
                ]
            })
            if (response && response.data) {
                customerBlogClass = response.data.map(item => { return item.content.blogClassId })
            }
        }

        await new Promise(resolve => {
            this.setState({
                user,
                blog,
                personClass,
                customerBlogClass
            }, resolve)
        })

        if (user) await new Promise(resolve => { this.setState({ loading: false }, resolve) })
    }

    //富文本变化
    onEditorChange = async (html, textValue) => {
        await new Promise(resolve => {
            this.setState({
                blog: {
                    ...this.state.blog,
                    blogText: textValue,
                    htmlText: html
                }
            }, resolve)
        })
    }

    //blog相关内容变化
    onChange = (fieldName) => {
        return async (value) => {
            await new Promise((resolve) => {
                this.setState({
                    blog: {
                        ...this.state.blog,
                        [fieldName]: value
                    }
                }, resolve)
            })
        }
    }

    //其他内容变化
    onOtherChange = (fieldName) => {
        return async (value) => {
            debugger
            await new Promise((resolve) => {
                this.setState({
                    [fieldName]: value
                }, resolve)
            })
        }
    }



    /**
     * 保存和暂存的逻辑
     * @param {0：暂存 1：保存} type 
     * @returns 
     */
    saveHandler = (type) => {
        return async () => {
            let blog = { ...this.state.blog }
            if (Array.isArray(blog.classify)) {
                blog.classify = JSON.stringify(blog.classify)
            }
            if (!blog.blogTitle) {
                message.warning('博客标题不能为空')
                return
            }
            //根据保存类型决定博客状态
            if (type === 0) {
                blog.state = '待发布'
            } else if (type === 1) {
                blog.state = '已发布'
            }
            //保存博客
            const response = await post(`/blog/save`, {
                body: JSON.stringify({
                    blog,
                    customerBlogClass: this.state.customerBlogClass
                })
            })
            if (response && response.data) {
                await new Promise(resolve => {
                    this.setState({ blog: response.data }, resolve)
                })
                message.success(`${type === 0 ? '暂存' : '发布'}成功`)
                if (type === 1) {
                    this.props.navigate(`/${this.props.user.id}/blog/${response.data.id}`) //发布后跳转blog浏览页面
                }
            } else {
                message.error(`${type === 0 ? '暂存' : '发布'}失败`)
            }
        }
    }

    render() {
        if (this.state.loading === true) return <Spin />
        return (
            <div className='blog-write-main'>
                <div className='blog-write-left'>
                    <div className='blog-write-editor'>
                        <EditorWidget
                            defaultHtml={this.state.blog.htmlText}
                            style={{ height: 'calc(100vh - 60px - 1.2em)', minHeight: '300px' }}
                            onChange={this.onEditorChange}
                        ></EditorWidget>
                    </div>
                </div>
                <div className='blog-write-right'>
                    <div className='blog-write-title'>
                        <InputWidget
                            hiddenClearButton={true}
                            prefixName={{ content: '标题' }}
                            onChange={this.onChange('blogTitle')}
                            value={this.state.blog.blogTitle}
                        ></InputWidget>
                    </div>
                    <div className='blog-write-type'>
                        <CheckBoxWidget
                            paramCode='blogType'
                            prefixName={{ content: '分类' }}
                            onChange={this.onChange('classify')}
                            value={this.state.blog.classify}
                            hiddenClearButton={true}
                        />
                    </div>
                    {
                        this.state.personClass.length > 0 ?
                            <div className='blog-write-type'>
                                <CheckBoxWidget
                                    paramCode='personClass'
                                    prefixName={{ content: '标签' }}
                                    paramItem={this.state.personClass.map(item => {
                                        return {
                                            id: item.id,
                                            code: item.id,
                                            content: item.className
                                        }
                                    })}
                                    onChange={this.onOtherChange('customerBlogClass')}
                                    value={this.state.customerBlogClass}
                                    hiddenClearButton={true}
                                />
                            </div> : ''
                    }
                    <div className='blog-write-button'>
                        <Button
                            onClick={this.saveHandler(0)}
                            style={{ marginRight: '1em' }}
                        >暂存</Button>
                        <Button
                            onClick={this.saveHandler(1)}
                        >发布</Button>
                    </div>
                </div>
            </div>
        )
    }
}

export default withRouterContext(getContext(WriteBlog))
